package com.bw.Controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.common.BResult;
import com.bw.common.JwtUtils;
import com.bw.domain.User;
import com.bw.service.HouseService;
import com.bw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
public class UserController {
    @Autowired
    HouseService houseService;
    @Autowired
    UserService userService;
    @RequestMapping("login")
  public BResult login(@RequestBody  User user, HttpServletResponse response){
        User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getName, user.getName()));
        if (one==null){
            return BResult.error("名字不正确");
        }
        if (!one.getPwd().equals(DigestUtil.md5Hex(user.getPwd()+salt))){
            return BResult.error("密码不正确");
        }
        String token = JwtUtils.createToken(one, 500);
        Cookie cookie = new Cookie("token", token);
        response.addCookie(cookie);
        return  BResult.success(token);
    }
    @RequestMapping("SelectByToken")
    public User SelectByToken(@RequestParam(defaultValue = "token",required = false)String token ){
        User user = JwtUtils.getLoginUserFromRequest(token, User.class);
        return  user;
    }
    public static final String salt="1234";
    @PostConstruct
    public void init(){
        String pwd="1234";
        String s = DigestUtil.md5Hex(pwd + pwd);

               System.out.println(s);
    }
}
